package com.fintech.pangu.security.authorize.impl;

import com.fintech.pangu.security.authorize.AuthorizeCacheSynchronizer;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

/**
 * 权限缓存同步器的初始化器
 * 依赖于Redis、RestTemplate等组件先装配好，在Spring容器Ready后再初始化
 */
public class AuthorizeCacheSynchronizerInitializer implements ApplicationListener<ApplicationReadyEvent> {

    // 权限缓存同步器，根据类型注入，同一时刻Spring容器中只应有一个
    private AuthorizeCacheSynchronizer authorizeCacheSynchronizer;

    // 同步器初次执行的延时(ms)
    private int initialDelayMs = 5 * 1000;

    // 执行间隔(ms)
    private int intervalMs = 30 * 1000;


    /**
     * 构造方法要传入权限缓存同步器，及初始化延时时间、执行间隔时间
     * @param authorizeCacheSynchronizer
     * @param initialDelayMs
     * @param intervalMs
     */
    public AuthorizeCacheSynchronizerInitializer(AuthorizeCacheSynchronizer authorizeCacheSynchronizer, int initialDelayMs, int intervalMs) {
        this.authorizeCacheSynchronizer = authorizeCacheSynchronizer;
        this.initialDelayMs = initialDelayMs;
        this.intervalMs = intervalMs;
    }

    /**
     * 在Spring容器准备就绪后，处理RBAC权限缓存数据的初始化
     * 调用远端RBAC服务后，同步数据到Redis
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 启动权限同步器
        authorizeCacheSynchronizer.start(initialDelayMs, intervalMs);
    }

}
